﻿using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FranceTriple.Dal;

namespace TeamFranceTriple
{
    public partial class ForumTopicList : BaseUserControl
    {
        public ForumSearchCriteria SearchCriteria { get; set; }

        private String searchLocalized = "searchResult".ToLocalizedString();
        private String lastpostLocalized = "lastpost".ToLocalizedString();
        private String orphanLocalized = "orphan".ToLocalizedString();
        private String lasttopicLocalized = "lasttopic".ToLocalizedString();
        private String unreadLocalized = "unread".ToLocalizedString();

        private Int32 UserRightLevel { get; set; }
        private Int32 ForumCategoryId { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            HyperLink1.NavigateUrl = String.Format("~/{0}/forum", ThisMaster.Requester.Culture);
            HyperLink2.NavigateUrl = String.Format("~/{0}/forum", ThisMaster.Requester.Culture);

            HyperLink3.NavigateUrl = String.Format("~/{0}/search", ThisMaster.Requester.Culture);
            HyperLink4.NavigateUrl = String.Format("~/{0}/topic/lastpost", ThisMaster.Requester.Culture);
            HyperLink5.NavigateUrl = String.Format("~/{0}/topic/orphan", ThisMaster.Requester.Culture);
            HyperLink6.NavigateUrl = String.Format("~/{0}/topic/lasttopic", ThisMaster.Requester.Culture);
            HyperLink7.NavigateUrl = String.Format("~/{0}/topic/lastpost", ThisMaster.Requester.Culture);
            HyperLink8.NavigateUrl = String.Format("~/{0}/search", ThisMaster.Requester.Culture);
            HyperLink9.NavigateUrl = String.Format("~/{0}/topic/lasttopic", ThisMaster.Requester.Culture);
            HyperLink10.NavigateUrl = String.Format("~/{0}/topic/orphan", ThisMaster.Requester.Culture);

            UnreadHyperLink.NavigateUrl = String.Format("~/{0}/topic/unread", ThisMaster.Requester.Culture);
            UnreadHyperLink2.NavigateUrl = String.Format("~/{0}/topic/unread", ThisMaster.Requester.Culture);
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            // Affichage d'une liste de sujets de discussion.
            DataSet ds=null;
            String viewType = String.Empty;

            if (Page.RouteData.Values["viewType"] != null)
                viewType = Page.RouteData.Values["viewType"].ToString();
            else
            {
                viewType = "bycategory";
            }

            if (viewType != null && viewType != String.Empty)
                switch (viewType)
                {
                    case "bycategory":
                        //Todo : Intercepter avec un TryParse l'erreur : Value was either too large or too small for an Int32.  
                        this.ForumCategoryId = Int32.Parse(Page.RouteData.Values["categoryId"].ToString());

                        var ThisCategory = ForumCategoryDal.GetEntity(ForumCategoryId);

                        if (ThisCategory == null)
                            throw new HttpException(404, String.Format("This category don't exists: {0}", ForumCategoryId.ToString()));

                        this.UserRightLevel = UserAccessDal.UserRightLevel(ForumCategoryId, ((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString()));
                        if (this.UserRightLevel == RightLevel.NoAccess)
                            Response.Redirect(String.Format("~/{0}/connexion/?returnurl=~{1}", ThisMaster.Requester.Culture, Request.RawUrl));

                        XmlForumTopic.GroupingText = String.Format("{0} {1}", XmlForumTopic.GroupingText, ThisCategory.LabelForumCategory);
                        // Topic d'une catégorie
                        ds = new ForumTopicView().GetXmlEntities(ForumCategoryId, (Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.Requester.Profile.TimeZone);
                        this.Page.Title = String.Format("{0}{1}", prefixTitle, ThisCategory.LabelForumCategory);
                        break;
                    case "unread":
                        //Topic non lu par currentuser
                        ds = new ForumTopicView().GetUnreadXmlEntities((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.Requester.Profile.TimeZone);
                        this.Page.Title = String.Format("{0}{1}", prefixTitle, unreadLocalized);
                        break;
                    case "lasttopic":
                        //Topic les plus recents
                        ds = new ForumTopicView().GetLastTopicCreateXmlEntities((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.Requester.Profile.TimeZone);
                        this.Page.Title = String.Format("{0}{1}", prefixTitle, lasttopicLocalized);
                        break;
                    case "lastpost":
                        //Topic les plus recents
                        ds = new ForumTopicView().GetLastPostCreateXmlEntities((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.Requester.Profile.TimeZone);
                        this.Page.Title = String.Format("{0}{1}", prefixTitle, lastpostLocalized);
                        break;
                    case "orphan":
                        //Topic sans réponse : 1 message et sujet non-vérouillé
                        ds = new ForumTopicView().GetOrphanXmlEntities((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.Requester.Profile.TimeZone);
                        this.Page.Title = String.Format("{0}{1}", prefixTitle, orphanLocalized);
                        break;
                    case "search":
                        //Recherche sur mot-clefs et liste d'auteurs
                        var criteria = Session["criteria"] as ForumSearchCriteria;
                        ds = new ForumTopicView().SearchByKeywordsAndAuthors(criteria.Keywords, criteria.Authors, (Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.Requester.Profile.TimeZone);
                        Session["criteria"] = null;
                        this.Page.Title = String.Format("{0}{1}", prefixTitle, searchLocalized);
                        break;
                    default:
                        break;
                }

            ChangeCategoryDropDownList1.DataSource = UserAccessDal.GetForumCategoryAllowedLookup((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString());
            ChangeCategoryDropDownList1.DataBind();
            ChangeCategoryDropDownList2.DataSource = UserAccessDal.GetForumCategoryAllowedLookup((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString());
            ChangeCategoryDropDownList2.DataBind();

            if (this.ForumCategoryId > 0)
            {
                ChangeCategoryDropDownList1.SelectedValue = this.ForumCategoryId.ToString();
                ChangeCategoryDropDownList2.SelectedValue = this.ForumCategoryId.ToString();
            }

            TopicListView.DataSource = ds.Tables["Topic"];
            TopicListView.DataBind();

            // Les utilisateurs anonymes n'ont pas accès à la fonctionnalité message non-lu, ni à la création de sujet
            if (Session["AnonymousID"] == null)
            {
                NewTopicHyperLink.Visible = true;
                NewTopicHyperLink.NavigateUrl = String.Format("~/{0}/topicdetail/{1}/0", ThisMaster.Requester.Culture, this.ForumCategoryId);
                NewTopicHyperLink2.Visible = true;
                NewTopicHyperLink2.NavigateUrl = String.Format("~/{0}/topicdetail/{1}/0", ThisMaster.Requester.Culture, this.ForumCategoryId);
                UnreadHyperLink.Visible = true;
                UnreadHyperLink2.Visible = true;
            }
            else
            {
                NewTopicHyperLink.Visible = false;
                NewTopicHyperLink2.Visible = false;
                UnreadHyperLink.Visible = false;
                UnreadHyperLink2.Visible = false;
            }
        }

        protected void TopicListView_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            HyperLink forumPostHyperLink;
            Int32 forumTopicId;
            ListView LastPostListView;
            DataRowView drv;
            ListViewItem item = e.Item;
            DataView view = null;
            Button btn, btn2;

            if (item.ItemType == ListViewItemType.DataItem)
            {
                btn = e.Item.FindControl("EditForumTopicButton") as Button;
                btn2 = e.Item.FindControl("DeleteForumTopicButton") as Button;

                // ForumPostHyperLink.NavigateUrl contient ForumTopicId
                forumPostHyperLink = (HyperLink)item.FindControl("ForumPostHyperLink");
                forumTopicId = Int32.Parse(forumPostHyperLink.NavigateUrl);

                this.UserRightLevel = UserAccessDal.UserRightLevel(ForumCategoryDal.GetCategoryIdByTopicId(forumTopicId), "");

                if (ThisMaster.Requester.Profile != null && ((ThisMaster.Requester.Profile.UserName.ToLower() == ForumTopicDal.GetEntity(forumTopicId).AuthorForumTopic.ToLower()
                    && btn != null && btn.CommandName == String.Empty) || (this.UserRightLevel == RightLevel.Moderator)))
                {
                    btn.Visible = true;
                    btn.CommandName = "EditCommand";
                    if (forumPostHyperLink.NavigateUrl != null && forumPostHyperLink.NavigateUrl != String.Empty)
                        btn.CommandArgument = forumPostHyperLink.NavigateUrl;
                }

                if (ThisMaster.Requester.Profile != null && (this.UserRightLevel == RightLevel.Moderator || ThisMaster.Requester.Profile.UserName.ToLower() == ForumTopicDal.GetEntity(forumTopicId).AuthorForumTopic.ToLower())
                    && btn2 != null && btn2.CommandName == String.Empty)
                {
                    btn2.Visible = true;
                    btn2.CommandName = "Delete";
                    if (forumPostHyperLink.NavigateUrl != null && forumPostHyperLink.NavigateUrl != String.Empty)
                        btn2.CommandArgument = forumPostHyperLink.NavigateUrl;
                }

                if (forumPostHyperLink != null)
                {
                    forumPostHyperLink.NavigateUrl = String.Format("~/{0}/forumpost/{1}/?topicpagenumber={2}"
                        , ThisMaster.Requester.Culture
                        , forumPostHyperLink.NavigateUrl
                        , ((Page.RouteData.Values["topicPageNumber"] != null) ? Page.RouteData.Values["topicPageNumber"].ToString() : String.Empty));
                }
                LastPostListView = (ListView)item.FindControl("LastPostListView");
                drv = (DataRowView)item.DataItem;

                if (drv != null && drv.DataView.Table.ChildRelations.Count > 0)
                    view = drv.CreateChildView("Topic_LastPost");

                if (view != null)
                {
                    LastPostListView.DataSource = view;
                    LastPostListView.DataBind();
                }
            }
        }

        protected void TopicListView_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "EditCommand")
            {
                var ForumTopicId = Int32.Parse(e.CommandArgument.ToString());
                var ForumCategoryId = ForumCategoryDal.GetCategoryIdByTopicId(ForumTopicId);
                Response.Redirect(String.Format("~/{0}/topicdetail/{1}/{2}", ThisMaster.Requester.Culture, ForumCategoryId, ForumTopicId));
            }

            if (e.CommandName == "Delete")
            {
                ForumTopicDal.DeleteEntity(Int32.Parse(e.CommandArgument.ToString()));
            }
        }

        protected void TopicListView_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {

        }

        protected void TopicListView_ItemDeleted(object sender, ListViewDeletedEventArgs e)
        {

        }

        protected void LastPostListView_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            TextBox forumCategoryIdLabel;
            HyperLink lastPostHyperLink;

            forumCategoryIdLabel = (TextBox)((ListViewItem)e.Item).FindControl("ForumCategoryIdLabel");
            lastPostHyperLink = (HyperLink)((ListViewItem)e.Item).FindControl("LastPostHyperLink");

            if (lastPostHyperLink != null && forumCategoryIdLabel != null)
                lastPostHyperLink.NavigateUrl = String.Format("~/{0}/forumpost/showpost/{1}/?topicpagenumber={2}"
                    , ThisMaster.Requester.Culture
                    , ((DataRowView)e.Item.DataItem).Row.ItemArray[3].ToString()
                    , ((Page.RouteData.Values["topicPageNumber"] != null) ? Page.RouteData.Values["topicPageNumber"].ToString() : String.Empty));
        }

        protected void ChangeCategoryDropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(String.Format("~/{0}/topic/bycategory/{1}", ThisMaster.Requester.Culture, ChangeCategoryDropDownList1.SelectedValue));
        }

        protected void ChangeCategoryDropDownList2_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(String.Format("~/{0}/topic/bycategory/{1}", ThisMaster.Requester.Culture, ChangeCategoryDropDownList2.SelectedValue));
        }
    }
}